import { RouteRecordRaw, Router } from "vue-router";
import { NOT_FOUND_ROUTE, basicRoutesName } from ".";
import { tokenUtils } from "@/utils";
import { useAuthStore, useRouteStore } from "@/store";

export const useAddDynamicRoutes = (router: Router) => {
  /** 添加动态路由 */
  const addDynamicRoutes = async () => {
    const token = tokenUtils.get();

    // 没有token情况
    if (!token) return;

    // 有token的情况
    const userStore = useAuthStore();
    await userStore.getUserInfo();

    if (!userStore.isLogin) {
      window.$message?.error("Token已过期，请重新登录");
      userStore.reLogin();
      return;
    }

    // 获取动态路由
    const routerStore = useRouteStore();
    const permsRoutes = await routerStore.getPermsRoutes();

    // 添加动态路由
    for (const route of permsRoutes) {
      if (router.hasRoute(route.name)) {
        console.error("存在重复的router：", route, router.getRoutes());
      } else {
        router.addRoute(route as RouteRecordRaw);
      }
    }

    // 将未定义路由匹配放置最后
    router.addRoute(NOT_FOUND_ROUTE as RouteRecordRaw);
  };

  /** 删除动态路由 */
  const resetRouter = async () => {
    router.getRoutes().forEach((route) => {
      const name = route.name as string;
      if (!basicRoutesName.includes(name)) {
        router.removeRoute(name);
      }
    });
  };
  return { addDynamicRoutes, resetRouter };
};
